Explain Variadic Function in Go Programming Language | Go Programming Tutorial
In this article, you will learn:
- What are the Variadic Functions in Go Programming Language?
- When to use Variadic Function?
What are the Variadic Functions in Go Programming Language?
The function that is called with a differing number of parameters is known as a variadic function. In simple words, a user can pass zero and multiple arguments in the variadic function.
fmt.Printf is an example of the variadic function. It requires one fixed argument initially after that it can accept any number of arguments.
Important Points: When we declare the variadic function, the type of the last parameter is preceded by(....). It represents that the function can be called any number of parameters of this specific type.
SYNTAX:
function function_name(parameter1, parameter2,.... type)type {
// set of statements
}
- The type inside the function is like a slice. All the parameters are of the same type.
- If you do not pass any argument in the variadic function, then the slice inside the function remains empty.
- The variadic functions are used for functions that perform string formatting.
- The user can also pass multiple slices in the variadic function.
- The user can not use variadic parameters as a return value, but you can return it as a slice.
Example 1:
package mainimport ( "fmt" "strings")// Variadic function to concat stringsfunc concatstr(elements ...string) string { return strings.Join(elements, "-")}func main() { // zero argument fmt.Println(joinstr()) // multiple arguments fmt.Println(concatstr("Tutorial", "Links")) fmt.Println(concatstr("L", "i", "n", "k", "S"))}OUTPUT:
Tutorial-Links
L-i-n-k-s
When to use the Variadic function?
- Variadic functions are used inside of just passing a slice to a function.
- It is used when the user is not aware of the number of parameters in the function.
- When users use variadic functions in your program, the readability of your program is increased.


